package com.seednia.module.util.messagesender.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seednia.foundation.framework.service.AbstractService;
import com.seednia.foundation.framework.util.PropertyLoader;
import com.seednia.module.util.messagesender.IMessageSender;
import com.seednia.module.util.messagesender.IMessageSenderService;

public class MessageSenderService  extends AbstractService implements IMessageSenderService {

	/**
	 * Map of different message sender providers
	 */
	private Map<String, IMessageSender> messageSenderMap = new HashMap<String, IMessageSender>();
	
	private static final Log logger = LogFactory.getLog(MessageSenderService.class);
	
	@Override
	public void initialize() {
		// Do any required initialization
		try {
			Properties config = PropertyLoader.loadProperties("message-providers.properties");
			String[] providers = config.getProperty("providers").split(",");
			for (String providerId: providers) {
				IMessageSender providerObj = (IMessageSender)instantiateObjectFromProp(config, "provider."+providerId+".class");
				providerObj.setId(providerId);
				providerObj.initialize(config);
				this.addMessageSender(providerId, providerObj);
			}
		} catch (Exception e) {
			logger.error("Exception while initializing message sender providers. ", e);
		}
	}

	private Object instantiateObjectFromProp(Properties props, String propName) throws ClassNotFoundException, InstantiationException, IllegalAccessException
	{
		String className = props.getProperty(propName);
		if (className == null)
			throw new IllegalArgumentException("No property of key "+propName+" was found.");
		Class<?> clazz = Class.forName(className);
		Object retval = clazz.newInstance(); 
		return retval;
	}
	
	@Override
	public IMessageSender getMessageSender(String id) {
		return messageSenderMap.get(id);
	}

	@Override
	public Collection<IMessageSender> getMessageSenders() {
		return this.messageSenderMap.values();
	}
	
	@Override
	public Collection<IMessageSender> getMessageSenders(int type) {
		List<IMessageSender> retval = new ArrayList<IMessageSender>();
		for ( IMessageSender senderEntry: this.getMessageSenderMap().values() )
		{
			if ( (senderEntry.getType() & type ) > 0 )
			{
				retval.add(senderEntry);
			}
		}
		return retval;
	}

	@Override
	public Map<String, IMessageSender> getMessageSenderMap() {
		return this.messageSenderMap;
	}

	public void addMessageSender(String id, IMessageSender messageSender) {
		this.getMessageSenderMap().put(id, messageSender);
	}
}
